<?php
class XA_File {



	public static function path($id) {
		return FILE_REPOSITORY_PATH . self::sub($id);
	}



	public static function sub($id) {
		$file_padded_name = str_pad($id, 6, '0', STR_PAD_LEFT);
		return substr($file_padded_name, 0, 3).'/'.substr($file_padded_name, 3, 3);
	}



	public static function update($file) {
		if (empty($file['path']) || !is_readable($file['path'])) {
			return false;
		}

		if (!empty($file['path'])) {
			$finfo = new finfo(FILEINFO_MIME_TYPE);
			$file['type'] = $finfo->file($file['path']);

			$file_dir = dirname($file_save_path = self::path($file['file_id']));

			if (!is_writable($file_dir)) {
				if (!mkdir($file_dir, 0777, true)) {
					trigger_error('Could not create directory '.$file_dir, E_USER_ERROR);
					die();
				}
			}

			if (is_uploaded_file($file['path'])) {
				move_uploaded_file($file['path'], $file_save_path);
			} else {
				copy($file['path'], $file_save_path);
			}
		}

		xa::table('file')->update($file) or e(xa::table('file')->error_list);

		return true;
	}



	public static function add($path, $name) {
		if (is_readable($path)) {
			$finfo = new finfo(FILEINFO_MIME_TYPE);

			$file_id = xa::query("
				INSERT INTO file (name, type) VALUES (
					  '".xa_db::esc($name)."'
					, '".xa_db::esc($finfo->file($path))."'
				)
			");

			$file_dir = dirname($file_save_path = self::path($file_id));

			if (!file_exists($file_dir)) {
				if (!mkdir($file_dir, 0777, true)) {
					trigger_error('Could not create directory '.$file_dir, E_USER_ERROR);
					die();
				}
			}

			if (!is_writable($file_dir)) {
				trigger_error('Could not write to directory '.$file_dir, E_USER_ERROR);
				die();
			}

			if (is_uploaded_file($path)) {
				move_uploaded_file($path, $file_save_path);
			} else {
				copy($path, $file_save_path);
			}

			chmod($file_save_path, 0666);

			return $file_id;
		}

		return false;
	}



	public static function receive($field_name) {
		return 
			empty($_FILES[$field_name])
			? false
			: self::add($_FILES[$field_name]['tmp_name'], $_FILES[$field_name]['name']);
	}



	public static function remove($id) {
		$id = xa_in::nat($id);
		xa::query("DELETE FROM file WHERE file_id = $id LIMIT 1");
		if (file_exists(self::path($id))) {
			unlink(self::path($id));
		}
	}



	public function get($id) {
		$id = xa_in::nat($id);
		return xa::query("SELECT * FROM file WHERE file_id = $id LIMIT 1")->row() + array('path' => self::path($id));
	}
}
